package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.client.MyFeignClient;
import com.hmall.search.common.dto.Item;
import com.hmall.search.common.dto.ItemDoc;
import com.hmall.search.common.dto.PageDTO;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    MyFeignClient feignClient;
    @Override
    public List<String> getSuggestions(String key) {
        SearchRequest request = new SearchRequest("item");
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("itemSuggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                .prefix(key)
                                .skipDuplicates(true)
                                .size(10)
                ));
        ArrayList<String> suggestionList = new ArrayList<>();
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("itemSuggestion");
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                String s = option.getText().toString();
                suggestionList.add(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(suggestionList);
        return suggestionList;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> getList(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(requestParams, request);
            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("发生了{}错误", e.getMessage());
        }
        return null;
    }

    @Override
    public void delete(Long id) {
        Item item = feignClient.findById(id);
        item.setStatus(2);
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insert(Long id) {
        Item item = feignClient.findById(id);
        //转化为文档类型
        item.setStatus(1);
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(50)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(50)
        );
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNoneBlank(key)) {     //不为空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
            request.source().query(QueryBuilders.matchQuery("all", key));
            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        } else {//todo 为空
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        //品牌
        if (StringUtils.isNoneBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //分类
        if (StringUtils.isNoneBlank(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //价格
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()*100).gte(params.getMinPrice()*100));
        }

        // 2.2.分页
        Long page = params.getPage();
        int size = params.getSize();
        request.source().from((int) ((page - 1) * size)).size(size);

        if (params.getSortBy().equalsIgnoreCase("default")) {
            // 2.算分控制
            FunctionScoreQueryBuilder functionScoreQuery =
                    QueryBuilders.functionScoreQuery(
                            // 原始查询，相关性算分的查询
                            boolQuery,
                            // function score的数组
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                    // 其中的一个function score 元素
                                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                            // 过滤条件
                                            QueryBuilders.termQuery("isAD", true),
                                            // 算分函数
                                            ScoreFunctionBuilders.weightFactorFunction(5)
                                    )
                            });
            request.source().query(functionScoreQuery);
        }
//        request.source().query(boolQuery);

    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) throws IOException {

        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            String json = hit.getSourceAsString();
            ItemDoc hotelDoc = JSON.parseObject(json, ItemDoc.class);
            hotels.add(hotelDoc);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    System.out.println(name);
                    // 覆盖非高亮结果
                    hotelDoc.setName(name);
                }
            }
        }
        return new PageDTO(total, hotels);
    }
}
